/*
pthread_cond_t
pthread_cond_init(&cond,nullptr)
pthread_cond_wait(&cond,&mutex)
pthread_cond_signal(&cond,&mutex)
pthread_cond_broadcast(&cond)
pthread_cond_destroy(&cond)
*/

#include <iostream>
#include <pthread.h>
#include <unistd.h>


using namespace std;


pthread_mutex_t mutex;
pthread_cond_t cond;
bool ready = false;


void* waitForSignal(void* arg)
{
	pthread_mutex_lock(&mutex);
	while(!ready) //if other threads get resource, here use "while" instead of "if"
	{
		//cond wait will releas mutex and sleep,when cond signal come ,it will wakeup and try to get mutex again!
		pthread_cond_wait(&cond,&mutex);
	}

	cout << "signal recv" << endl;

	pthread_mutex_unlock(&mutex);

	return nullptr;
}


void* sendSignal(void* arg)
{
	pthread_mutex_lock(&mutex);
	ready = true;
	pthread_cond_signal(&cond);
	pthread_mutex_unlock(&mutex);
	return nullptr;
}

int main(int argc,char** argv)
{
	pthread_t t1,t2;

	pthread_mutex_init(&mutex,nullptr);
	pthread_cond_init(&cond,nullptr);

	pthread_create(&t1,nullptr,waitForSignal,nullptr);
	pthread_create(&t2,nullptr,sendSignal,nullptr);

	pthread_join(t1,nullptr);
	pthread_join(t2,nullptr);

	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);

	return 0;
}


